<script setup lang="ts">
import type { BlogArticleListItem } from '~/types/blog'
import { computed, ref } from 'vue'
import ArcanumLayout from '~/components/ArcanumLayout.vue'
import {
  useArticleList,
  useBlogCategories,
  useBlogTags,
  useSiteInfo,
} from '~/composables/useBlog'

const { siteInfo } = useSiteInfo()
const { categories, loading: categoriesLoading } = useBlogCategories()
const { tags } = useBlogTags()

const {
  articles,
  loading: articlesLoading,
  total,
  setFilters,
} = useArticleList({ pageSize: 7 })

const selectedCategoryId = ref<number | null>(null)
const selectedTagId = ref<number | null>(null)

const featuredArticle = computed(() => articles.value[0] ?? null)
const secondaryArticles = computed(() => articles.value.slice(1))

const tagNameMap = computed(() => new Map(tags.value.map(tag => [tag.tagId, tag.name])))

const heroTitle = computed(() => siteInfo.value?.heroTitle ?? '夜读工坊 · 以学者视角构建现代前端知识库')
const heroSubtitle = computed(() => siteInfo.value?.heroSubtitle ?? '以学者之姿，雕刻你的数字知识基地')
const heroDescription = computed(() => siteInfo.value?.heroDescription ?? '夜读工坊聚焦设计系统、知识架构与工程策略，让若依后端的真实数据化为可执行的前端体验。')
const primaryCtaText = computed(() => siteInfo.value?.ctaText ?? '探索文章')
const primaryCtaLink = computed(() => siteInfo.value?.ctaLink ?? '/article')
const secondaryCtaText = computed(() => siteInfo.value?.secondaryCtaText ?? '认识作者')
const secondaryCtaLink = computed(() => siteInfo.value?.secondaryCtaLink ?? '/about')

const curatedTopics = computed(() => {
  const names = tags.value.map(tag => tag.name).filter(Boolean)
  if (names.length === 0)
    return ['设计语言', '知识星图', '工程工具', '体验度量', '思维模型']

  return names.slice(0, 8)
})

const isLoadingArticles = computed(() => articlesLoading.value)
const showEmptyState = computed(() => !isLoadingArticles.value && articles.value.length === 0 && !categoriesLoading.value)
const hasActiveFilters = computed(() => selectedCategoryId.value !== null || selectedTagId.value !== null)

useHead(() => ({
  title: heroTitle.value,
  meta: [
    {
      name: 'description',
      content: heroDescription.value,
    },
  ],
}))

function formatDate(timestamp?: string) {
  if (!timestamp)
    return '发布时间待定'

  try {
    return timestamp.split(' ')[0]
  }
  catch (error) {
    console.warn('[Date] Failed to format timestamp', error)
    return timestamp
  }
}

function estimateReadingMinutes(article: BlogArticleListItem) {
  const content = (article.summary || article.content || '').replace(/<[^>]+>/g, '')
  if (!content.length)
    return '约 3 分钟'

  const minutes = Math.max(3, Math.round(content.length / 500))
  return `约 ${minutes} 分钟`
}

function articleCategories(article: BlogArticleListItem) {
  return article.categoryName ? [article.categoryName] : []
}

function articleTags(article: BlogArticleListItem) {
  if (!article.tagIds || article.tagIds.length === 0)
    return []

  return article.tagIds
    .map(id => tagNameMap.value.get(id))
    .filter((name): name is string => Boolean(name))
}

function toggleCategory(categoryId: number | null) {
  selectedCategoryId.value = selectedCategoryId.value === categoryId ? null : categoryId
  setFilters({ categoryId: selectedCategoryId.value })
}

function toggleTag(tagId: number | null) {
  selectedTagId.value = selectedTagId.value === tagId ? null : tagId
  setFilters({ tagId: selectedTagId.value })
}

function resetFilters() {
  selectedCategoryId.value = null
  selectedTagId.value = null
  setFilters({ categoryId: null, tagId: null })
}
</script>

<template>
  <ArcanumLayout>
    <section class="flex flex-col gap-12 lg:flex-row lg:items-end">
      <div class="flex-1 space-y-6">
        <span class="brand-badge">夜读志</span>
        <p class="eyebrow-muted-sm">
          {{ heroSubtitle }}
        </p>
        <h1 class="hero-title">
          {{ heroTitle }}
        </h1>
        <p class="hero-lead">
          {{ heroDescription }}
        </p>
        <div class="stack-responsive-between-4">
          <RouterLink class="brand-button" :to="primaryCtaLink">
            {{ primaryCtaText }}
            <div class="i-heroicons-arrow-right-20-solid text-base" />
          </RouterLink>
          <RouterLink
            v-if="secondaryCtaLink"
            class="line-button"
            :to="secondaryCtaLink"
          >
            {{ secondaryCtaText }}
            <div class="i-heroicons-user-circle-20-solid text-base" />
          </RouterLink>
        </div>
      </div>

      <article v-if="featuredArticle" class="group max-w-xl self-stretch surface-card">
        <p class="card-meta">
          {{ formatDate(featuredArticle.createTime) }} · {{ estimateReadingMinutes(featuredArticle) }}
        </p>
        <RouterLink :to="`/article/${featuredArticle.articleId}`" class="mt-4 block">
          <h2 class="card-title">
            {{ featuredArticle.title }}
          </h2>
        </RouterLink>
        <p class="mt-4 text-base body-muted-sm">
          {{ featuredArticle.summary || '这篇文章正在整理简介，敬请期待。' }}
        </p>
        <div class="mt-6 flex flex-wrap gap-3">
          <span
            v-for="category in articleCategories(featuredArticle)"
            :key="category"
            class="tag-pill"
          >
            {{ category }}
          </span>
          <span
            v-for="tag in articleTags(featuredArticle)"
            :key="tag"
            class="tag-pill"
          >
            {{ tag }}
          </span>
        </div>
        <RouterLink :to="`/article/${featuredArticle.articleId}`" class="mt-8 w-max brand-button">
          阅读精选
          <div class="i-heroicons-book-open-20-solid text-base" />
        </RouterLink>
      </article>
      <article v-else class="max-w-xl self-stretch surface-card">
        <div class="h-full flex flex-col animate-pulse gap-5">
          <div class="h-4 w-32 rounded-full bg-border-light/70 dark:bg-border-dark/60" />
          <div class="h-8 w-3/4 rounded bg-border-light/80 dark:bg-border-dark/70" />
          <div class="space-y-3">
            <div class="h-4 w-full rounded bg-border-light/60 dark:bg-border-dark/50" />
            <div class="h-4 w-5/6 rounded bg-border-light/50 dark:bg-border-dark/40" />
          </div>
          <div class="mt-auto h-10 w-32 rounded-full bg-border-light/70 dark:bg-border-dark/70" />
        </div>
      </article>
    </section>

    <section id="latest" class="mt-20 space-y-10">
      <header class="section-heading">
        <h2 class="text-3xl section-title">
          最新洞察
        </h2>
        <p class="section-subtitle">
          从若依后端实时获取的文章，覆盖设计系统、知识管理与工程实践。
        </p>
      </header>

      <div v-if="categories.length || tags.length" class="gap-6 surface-card">
        <div class="flex flex-wrap items-center justify-between gap-4">
          <div class="space-y-1">
            <p class="tracking-[0.35em] uppercase text-muted-xs">
              智能筛选
            </p>
            <h3 class="text-lg text-text-base-light font-semibold dark:text-text-base-dark">
              聚焦你关心的分类与标签
            </h3>
          </div>
          <button
            v-if="hasActiveFilters"
            type="button"
            class="filter-reset"
            @click="resetFilters"
          >
            <div class="i-heroicons-arrow-path-20-solid text-base" />
            重置筛选
          </button>
        </div>

        <div class="grid gap-6 lg:grid-cols-2">
          <div v-if="categories.length" class="space-y-3">
            <p class="text-text-muted-light tracking-[0.3em] uppercase text-muted-xs dark:text-text-muted-dark">
              分类
            </p>
            <div class="flex flex-wrap gap-2">
              <button
                type="button"
                class="filter-chip"
                :class="{ 'filter-chip-active': selectedCategoryId === null }"
                :aria-pressed="selectedCategoryId === null"
                @click="toggleCategory(null)"
              >
                全部分类
              </button>
              <button
                v-for="category in categories"
                :key="category.categoryId"
                type="button"
                class="filter-chip"
                :class="{ 'filter-chip-active': selectedCategoryId === category.categoryId }"
                :aria-pressed="selectedCategoryId === category.categoryId"
                @click="toggleCategory(category.categoryId)"
              >
                {{ category.name }}
              </button>
            </div>
          </div>

          <div v-if="tags.length" class="space-y-3">
            <p class="text-text-muted-light tracking-[0.3em] uppercase text-muted-xs dark:text-text-muted-dark">
              标签
            </p>
            <div class="flex flex-wrap gap-2">
              <button
                type="button"
                class="filter-chip"
                :class="{ 'filter-chip-active': selectedTagId === null }"
                :aria-pressed="selectedTagId === null"
                @click="toggleTag(null)"
              >
                全部标签
              </button>
              <button
                v-for="tag in tags"
                :key="tag.tagId"
                type="button"
                class="filter-chip"
                :class="{ 'filter-chip-active': selectedTagId === tag.tagId }"
                :aria-pressed="selectedTagId === tag.tagId"
                @click="toggleTag(tag.tagId)"
              >
                {{ tag.name }}
              </button>
            </div>
          </div>
        </div>
      </div>

      <div v-if="isLoadingArticles" class="grid gap-8 md:grid-cols-2">
        <div v-for="skeleton in 4" :key="skeleton" class="animate-pulse surface-card">
          <div class="h-3 w-24 rounded-full bg-border-light/60 dark:bg-border-dark/60" />
          <div class="mt-4 h-6 w-3/4 rounded bg-border-light/70 dark:bg-border-dark/70" />
          <div class="mt-4 space-y-2">
            <div class="h-4 w-full rounded bg-border-light/60 dark:bg-border-dark/60" />
            <div class="h-4 w-5/6 rounded bg-border-light/50 dark:bg-border-dark/50" />
          </div>
          <div class="mt-6 flex gap-2">
            <div class="h-6 w-20 rounded-full bg-border-light/60 dark:bg-border-dark/60" />
            <div class="h-6 w-20 rounded-full bg-border-light/40 dark:bg-border-dark/40" />
          </div>
        </div>
      </div>

      <div v-else-if="showEmptyState" class="text-center surface-card">
        <h3 class="text-2xl card-title">
          暂无符合条件的文章
        </h3>
        <p class="mt-4 text-sm text-text-muted-light dark:text-text-muted-dark">
          尝试切换筛选条件或稍后再来，后台正在完善新的内容。
        </p>
      </div>

      <div v-else class="grid gap-8 md:grid-cols-2">
        <article
          v-for="article in secondaryArticles"
          :key="article.articleId"
          class="group surface-card"
        >
          <RouterLink :to="`/article/${article.articleId}`" class="block">
            <p class="card-meta">
              {{ formatDate(article.createTime) }} · {{ estimateReadingMinutes(article) }}
            </p>
            <h3 class="mt-4 card-title">
              {{ article.title }}
            </h3>
            <p class="mt-4 body-muted-sm">
              {{ article.summary || '这篇文章暂未提供摘要，点击查看完整内容。' }}
            </p>
            <div class="mt-6 flex flex-wrap gap-3">
              <span
                v-for="category in articleCategories(article)"
                :key="category"
                class="tag-pill"
              >
                {{ category }}
              </span>
              <span
                v-for="tag in articleTags(article)"
                :key="tag"
                class="tag-pill"
              >
                {{ tag }}
              </span>
            </div>
          </RouterLink>
        </article>
      </div>

      <footer v-if="total > secondaryArticles.length + (featuredArticle ? 1 : 0)" class="flex flex-col items-center gap-4 text-center">
        <p class="text-muted-sm">
          共 {{ total }} 篇文章，使用筛选器探索更多内容。
        </p>
        <RouterLink to="/article" class="line-button">
          浏览全部文章
          <div class="i-heroicons-squares-2x2-20-solid text-base" />
        </RouterLink>
      </footer>
    </section>

    <section class="group mt-20 surface-card">
      <div class="stack-responsive-between-6">
        <div class="space-y-3">
          <h2 class="text-2xl section-title">
            策展阅读清单
          </h2>
          <p class="text-base hero-lead md:max-w-xl">
            按标签自动聚合的主题清单，帮助你从不同维度梳理值得深读的文章、论文与工具。
          </p>
        </div>
        <RouterLink to="/newsletter" class="brand-button">
          订阅夜间通讯
          <div class="i-heroicons-envelope-20-solid text-base" />
        </RouterLink>
      </div>
      <div class="mt-8 flex flex-wrap gap-3">
        <span v-for="topic in curatedTopics" :key="topic" class="tag-pill">
          {{ topic }}
        </span>
      </div>
    </section>
  </ArcanumLayout>
</template>
